/*
	topic model
	@author guoqing.ma
*/
var mongodb = require('./db');
var BSON = require('mongodb');

function  Topic(topic){
	this._id = topic._id;
	this.title = topic.title;
	this.content = topic.content;
	this.time = new Date();
	this.userId = topic.userId;
	this.userName = topic.userName;
}

module.exports = Topic;

Topic.save = function save(topic,callback){
	mongodb.open(function(err,col){
		if(err){
			return callback;
		}
		col.collection('topic',function(err,collection){
			if(err){
				mongodb.close();
				return callback(err);
			}
			collection.insert(topic,{safe:true},function(err,topic){
				mongodb.close();
				callback(err,topic);
			});
		});
	});
};

Topic.getTopics = function(username,callback){
	mongodb.open(function(err,db){
		if(err){
			return callback(err);
		}
		db.collection('topic',function(err,collection){
			if(err){
				mongodb.close();
				return callback(err);
			}
			var query = {};
			if(username){
				query.userName = username;
			}
			collection.find(query).sort({time:-1}).toArray(function(err,docs){
				mongodb.close();
				if(err){
					callback(err,null);
				}
				var topics = [];
				docs.forEach(function(doc,index){
					var topic = new Topic(doc);
					topics.push(topic);
				});
				callback(null,topics);
			});
		});
	});
};

Topic.getTopicById = function(topicId,callback){
	mongodb.open(function(err,db){
		if(err){
			return callback(err);
		}
		db.collection('topic',function(err,collection){
			if(err){
				mongodb.close();
				return callback(err);
			}
			collection.findOne({"_id": BSON.ObjectID.createFromHexString(topicId)},function(err,docs){
				var topic = new Topic(docs);
				mongodb.close();
				callback(null,topic);
			});
		});
	});
};


